home *** CD-ROM | disk | FTP | other *** search
/ Tech Arsenal 1 / Tech Arsenal (Arsenal Computer).ISO / tek-01 / ohlutil.zip / DU.C < prev    next >
C/C++ Source or Header  |  1990-06-23  |  16KB  |  676 lines

  1. /* du -- summarize disk usage
  2.    Copyright (C) 1988, 1989, 1990 Free Software Foundation, Inc.
  3.  
  4.    This program is free software; you can redistribute it and/or modify
  5.    it under the terms of the GNU General Public License as published by
  6.    the Free Software Foundation; either version 1, or (at your option)
  7.    any later version.
  8.  
  9.    This program is distributed in the hope that it will be useful,
  10.    but WITHOUT ANY WARRANTY; without even the implied warranty of
  11.    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  12.    GNU General Public License for more details.
  13.  
  14.    You should have received a copy of the GNU General Public License
  15.    along with this program; if not, write to the Free Software
  16.    Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.  */
  17.  
  18. /* Differences from the Unix du:
  19.    * Doesn't simply ignore the names of regular files given as arguments
  20.      when -a is given.
  21.    * New option -l makes du count the size of all files, even if
  22.      they have appeared already in another hard link.
  23.    * New option -f makes du not cross file-system boundaries
  24.      during the recursion.
  25.    * New option -c to write a grand total of all of the arguments
  26.      after all arguments have been processed.  This can be used
  27.      to find out the disk usage of a directory, with some files excluded.
  28.    * New option -k to print sizes in kilobytes instead of the system's
  29.      blocksize.
  30.  
  31.    To do:
  32.    * Simpler path-handling, with no more copying overhead.
  33.  
  34.    By tege@sics.se, Torbjorn Granlund.   */
  35.  
  36. #include <stdio.h>
  37. #include <errno.h>
  38. #include <sys/types.h>
  39. #include "system.h"
  40. #include "getopt.h"
  41.  
  42. #ifdef STDC_HEADERS
  43. #include <stdlib.h>
  44. #else
  45. char *malloc ();
  46. char *realloc ();
  47.  
  48. extern int errno;
  49. #endif
  50.  
  51. /* Initial number of entries in each hash table entry's table of inodes.  */
  52.  
  53. #define INITIAL_HASH_MODULE 100
  54.  
  55. /* Initial number of entries in the inode hash table.  */
  56.  
  57. #define INITIAL_ENTRY_TAB_SIZE 70
  58.  
  59. /* Initial size to allocate for `path'.  */
  60.  
  61. #define INITIAL_PATH_SIZE 100
  62.  
  63. /* Hash structure for inode and device numbers.  The separate entry
  64.    structure makes it easier to rehash "in place".  */
  65.  
  66. struct entry
  67. {
  68.   ino_t ino;
  69.   dev_t dev;
  70.   struct entry *coll_link;
  71. };
  72.  
  73. /* Structure for a hash table for inode numbers. */
  74.  
  75. struct htab
  76. {
  77.   unsigned modulus;        /* Size of the `hash' pointer vector.  */
  78.   struct entry *entry_tab;    /* Pointer to dynamically growing vector.  */
  79.   unsigned entry_tab_size;    /* Size of current `entry_tab' allocation.  */
  80.   unsigned first_free_entry;    /* Index in `entry_tab'.  */
  81.   struct entry *hash[1];    /* Vector of pointers in `entry_tab'.  */
  82. };
  83.  
  84.  
  85. /* Structure for dynamically resizable strings. */
  86.  
  87. typedef struct
  88. {
  89.   unsigned alloc;        /* Size of allocation for the text.  */
  90.   unsigned length;        /* Length of the text currently.  */
  91.   char *text;            /* Pointer to the text.  */
  92. } *string, stringstruct;
  93.  
  94. char *savedir ();
  95. char *xmalloc ();
  96. char *xrealloc ();
  97. int hash_insert ();
  98. int hash_insert2 ();
  99. long count_entry ();
  100. void error ();
  101. void hash_init ();
  102. void hash_reset ();
  103. void str_concatc ();
  104. void str_copyc ();
  105. void str_init ();
  106. void str_trunc ();
  107.  
  108. /* Name under which this program was invoked.  */
  109.  
  110. char *program_name;
  111.  
  112. /* Booleans for option flags.  */
  113.  
  114. /* If nonzero, display only a grand total for each argument. */
  115.  
  116. int opt_summarize_only = 0;
  117.  
  118. /* If nonzero, display counts for all files, not just directories. */
  119.  
  120. int opt_all = 0;
  121.  
  122. /* If nonzero, count each hard link of files with multiple links. */
  123.  
  124. int opt_count_all = 0;
  125.  
  126. /* If nonzero, do not cross file-system boundaries. */
  127.  
  128. int opt_one_file_system = 0;
  129.  
  130. /* If nonzero, print a grand total at the end. */
  131.  
  132. int opt_combined_arguments = 0;
  133.  
  134. /* If nonzero, display 1K blocks instead of system defined blocks. */
  135.  
  136. int opt_kilobyte_blocks = 0;
  137.  
  138. /* Accumulated path for file or directory being processed.  */
  139.  
  140. string path;
  141.  
  142. /* Pointer to hash structure, used by the hash routines.  */
  143.  
  144. struct htab *htab;
  145.  
  146. /* Globally used stat buffer.  */
  147.  
  148. struct stat stat_buf;
  149.  
  150. /* Structure containing long-named options available at command line,
  151.    for use with getopt_long */
  152.  
  153. struct option long_options[] =
  154. {
  155.   {"all", 0, &opt_all, 1},
  156.   {"count-links", 0, &opt_count_all, 1},
  157.   {"kilobyte-file-size", 0, &opt_kilobyte_blocks, 1},
  158.   {"one-file-system", 0, &opt_one_file_system, 1},
  159.   {"summarize", 0, &opt_summarize_only, 1},
  160.   {"total", 0, &opt_combined_arguments, 1},
  161.   {NULL, 0, NULL, 0}
  162. };
  163.  
  164. void
  165. usage (reason)
  166.      char *reason;
  167. {
  168.   if (reason != NULL)
  169.     fprintf (stderr, "%s: %s\n", program_name, reason);
  170.  
  171.   fprintf (stderr, "\
  172. Usage: %s [-acfkls] [+all] [+total] [+one-file-system] [+count-links]\n\
  173.        [+summarize] [+kilobyte-file-size] [path...]\n", program_name);
  174.  
  175.   exit (2);
  176. }
  177.  
  178.  
  179. void
  180. main (argc, argv)
  181.      int argc;
  182.      char *argv[];
  183. {
  184.   int c;
  185.   int ind;
  186.  
  187.   program_name = argv[0];
  188.  
  189.   while ((c = getopt_long (argc, argv, "acfkls", long_options, &ind)) != EOF)
  190.     {
  191.       switch (c)
  192.     {
  193.     case 0:            /* Long option. */
  194.       break;
  195.  
  196.     case 'a':
  197.       opt_all = 1;
  198.       break;
  199.  
  200.     case 'c':
  201.       opt_combined_arguments = 1;
  202.       break;
  203.  
  204.     case 'f':
  205.       opt_one_file_system = 1;
  206.       break;
  207.  
  208.     case 'k':
  209.       opt_kilobyte_blocks = 1;
  210.       break;
  211.  
  212.     case 'l':
  213.       opt_count_all = 1;
  214.       break;
  215.  
  216.     case 's':
  217.       opt_summarize_only = 1;
  218.       break;
  219.  
  220.     default:
  221.       usage ((char *) 0);
  222.     }
  223.     }
  224.  
  225.   if (opt_all && opt_summarize_only)
  226.     usage ("cannot both summarize and show all entries");
  227.  
  228.  
  229.   /* Initialize the hash structure for inode numbers.  */
  230.  
  231.   hash_init (INITIAL_HASH_MODULE, INITIAL_ENTRY_TAB_SIZE);
  232.  
  233.   str_init (&path, INITIAL_PATH_SIZE);
  234.  
  235.   if (optind == argc)
  236.     {
  237.       str_copyc (path, ".");
  238.  
  239.       /* Initialize the hash structure for inode numbers.  */
  240.  
  241.       hash_reset ();
  242.  
  243.       /* Get the size of the current directory only.  */
  244.  
  245.       count_entry (".", 1, 0);
  246.     }
  247.   else
  248.     {
  249.       char wd[PATH_MAX + 2];
  250.       char *arg;
  251.       ino_t initial_ino;    /* Initial directory's inode. */
  252.       dev_t initial_dev;    /* Initial directory's device. */
  253.       long tot_size = 0;    /* Grand total size of all args. */
  254.  
  255.       if (getwd (wd) == NULL)
  256.     error (1, errno, "cannot get current directory");
  257.  
  258.       /* Remember the inode and device number of the current directory.  */
  259.  
  260.       if (stat (".", &stat_buf))
  261.     error (1, errno, "current directory");
  262.       initial_ino = stat_buf.st_ino;
  263.       initial_dev = stat_buf.st_dev;
  264.  
  265.       do
  266.     {
  267.       int s;
  268.       arg = argv[optind];
  269.  
  270.       /* Delete final slash in the argument, unless the slash is alone.  */
  271.  
  272.       s = strlen (arg) - 1;
  273.       if (s != 0)
  274.         {
  275.           if (arg[s] == '/')
  276.         arg[s] = 0;
  277.  
  278.           str_copyc (path, arg);
  279.         }
  280.       else if (arg[0] == '/')
  281.         str_trunc (path, 0);/* Null path for root directory.  */
  282.       else
  283.         str_copyc (path, arg);
  284.  
  285.       if (!opt_combined_arguments)
  286.         hash_reset ();
  287.  
  288.       tot_size += count_entry (arg, 1, 0);
  289.  
  290.       /* Chdir if `count_entry' has changed the working directory.  */
  291.  
  292.       if (stat (".", &stat_buf))
  293.         error (1, errno, ".");
  294.       if (stat_buf.st_ino != initial_ino || stat_buf.st_dev != initial_dev)
  295.         if (chdir (wd) < 0)
  296.           error (1, errno, "cannot change to directory %s", wd);
  297.  
  298.       optind++;
  299.     }
  300.       while (optind < argc);
  301.  
  302.       if (opt_combined_arguments)
  303.     {
  304.       printf (" %ld\ttotal\n",
  305.           convert_blocks (tot_size, opt_kilobyte_blocks));
  306.       fflush (stdout);
  307.     }
  308.     }
  309.   exit (0);
  310. }
  311.  
  312.  
  313.  
  314. /* Print (if appropriate) and return the size in blocks of
  315.    file or directory ENT.
  316.    TOP is one for external calls, zero for recursive calls.
  317.    LAST_DEV is the device that the parent dir of ENT is on.  */
  318.  
  319. long
  320. count_entry (ent, top, last_dev)
  321.      char *ent;
  322.      int top;
  323.      dev_t last_dev;
  324. {
  325.   long size;
  326.  
  327.   if (lstat (ent, &stat_buf) < 0)
  328.     {
  329.       error (0, errno, "%s", path->text);
  330.       return 0;
  331.     }
  332.  
  333.   if (!opt_count_all
  334.       && stat_buf.st_nlink > 1
  335.       && hash_insert (stat_buf.st_ino, stat_buf.st_dev))
  336.     return 0;            /* Have counted this already.  */
  337.  
  338.   size = ST_NBLOCKS (stat_buf);
  339. #ifdef HPUX_NFS_BUG
  340.   if (size >= 2 * (stat_buf.st_size + DEV_BSIZE - 1) / DEV_BSIZE)
  341.     size = (size + 1) / 2;
  342. #endif
  343.  
  344.   if ((stat_buf.st_mode & S_IFMT) == S_IFDIR)
  345.     {
  346.       unsigned pathlen;
  347.       dev_t dir_dev;
  348.       char *name_space;
  349.       char *namep;
  350.  
  351.       dir_dev = stat_buf.st_dev;
  352.  
  353.       if (opt_one_file_system && !top && last_dev != dir_dev)
  354.     return 0;        /* Don't enter a new file system.  */
  355.  
  356.       if (chdir (ent) < 0)
  357.     {
  358.       error (0, errno, "cannot change to directory %s", path->text);
  359.       return 0;
  360.     }
  361.  
  362.       errno = 0;
  363.       name_space = savedir (".", stat_buf.st_size);
  364.       if (name_space == NULL)
  365.     {
  366.       if (errno)
  367.         {
  368.           error (0, errno, "%s", path->text);
  369.           chdir ("..");    /* Try to return to previous directory.  */
  370.           return 0;
  371.         }
  372.       else
  373.         error (1, 0, "virtual memory exhausted");
  374.     }
  375.  
  376.       /* Remember the current path.  */
  377.  
  378.       str_concatc (path, "/");
  379.       pathlen = path->length;
  380.  
  381.       namep = name_space;
  382.       while (*namep != 0)
  383.     {
  384.       str_concatc (path, namep);
  385.  
  386.       size += count_entry (namep, 0, dir_dev);
  387.  
  388.       str_trunc (path, pathlen);
  389.       namep += strlen (namep) + 1;
  390.     }
  391.       free (name_space);
  392.       chdir ("..");
  393.  
  394.       if (!opt_summarize_only || top)
  395.     {
  396.       printf ("%ld\t%s\n",
  397.           convert_blocks (size, opt_kilobyte_blocks), path->text);
  398.       fflush (stdout);
  399.     }
  400.     }
  401.   else if (opt_all || top)
  402.     {
  403.       printf ("%ld\t%s\n",
  404.           convert_blocks (size, opt_kilobyte_blocks), path->text);
  405.       fflush (stdout);
  406.     }
  407.  
  408.   return size;
  409. }
  410.  
  411. /* Allocate space for the hash structures, and set the global
  412.    variable `htab' to point to it.  The initial hash module is specified in
  413.    MODULUS, and the number of entries are specified in ENTRY_TAB_SIZE.  (The
  414.    hash structure will be rebuilt when ENTRY_TAB_SIZE entries have been
  415.    inserted, and MODULUS and ENTRY_TAB_SIZE in the global `htab' will be
  416.    doubled.)  */
  417.  
  418. void
  419. hash_init (modulus, entry_tab_size)
  420.      unsigned modulus;
  421.      unsigned entry_tab_size;
  422. {
  423.   struct htab *htab_r;
  424.  
  425.   htab_r = (struct htab *)
  426.     xmalloc (sizeof (struct htab) + sizeof (struct entry *) * modulus);
  427.  
  428.   htab_r->entry_tab = (struct entry *)
  429.     xmalloc (sizeof (struct entry) * entry_tab_size);
  430.  
  431.   htab_r->modulus = modulus;
  432.   htab_r->entry_tab_size = entry_tab_size;
  433.   htab = htab_r;
  434.  
  435.   hash_reset ();
  436. }
  437.  
  438.  
  439. /* Reset the hash structure in the global variable `htab' to
  440.    contain no entries.  */
  441.  
  442. void
  443. hash_reset ()
  444. {
  445.   int i;
  446.   struct entry **p;
  447.  
  448.   htab->first_free_entry = 0;
  449.  
  450.   p = htab->hash;
  451.   for (i = htab->modulus; i > 0; i--)
  452.     *p++ = NULL;
  453. }
  454.  
  455.  
  456. /* Insert an item (inode INO and device DEV) in the hash
  457.    structure in the global variable `htab', if an entry with the same data
  458.    was not found already.  Return zero if the item was inserted and non-zero
  459.    if it wasn't.  */
  460. int
  461. hash_insert (ino, dev)
  462.      ino_t ino;
  463.      dev_t dev;
  464. {
  465.   struct htab *htab_r = htab;    /* Initially a copy of the global `htab'.  */
  466.  
  467.   if (htab_r->first_free_entry >= htab_r->entry_tab_size)
  468.     {
  469.       int i;
  470.       struct entry *ep;
  471.       unsigned modulus;
  472.       unsigned entry_tab_size;
  473.  
  474.       /* Increase the number of hash entries, and re-hash the data.
  475.      The method of shrimping and increasing is made to compactify
  476.      the heap.  If twice as much data would be allocated
  477.      straightforwardly, we would never re-use a byte of memory.  */
  478.  
  479.       /* Let `htab' shrimp.  Keep only the header, not the pointer vector.  */
  480.  
  481.       htab_r = (struct htab *)
  482.     xrealloc ((char *) htab_r, sizeof (struct htab));
  483.  
  484.       modulus = 2 * htab_r->modulus;
  485.       entry_tab_size = 2 * htab_r->entry_tab_size;
  486.  
  487.       /* Increase the number of possible entries.  */
  488.  
  489.       htab_r->entry_tab = (struct entry *)
  490.     xrealloc ((char *) htab_r->entry_tab,
  491.          sizeof (struct entry) * entry_tab_size);
  492.  
  493.       /* Increase the size of htab again.  */
  494.  
  495.       htab_r = (struct htab *)
  496.     xrealloc ((char *) htab_r,
  497.          sizeof (struct htab) + sizeof (struct entry *) * modulus);
  498.  
  499.       htab_r->modulus = modulus;
  500.       htab_r->entry_tab_size = entry_tab_size;
  501.       htab = htab_r;
  502.  
  503.       i = htab_r->first_free_entry;
  504.  
  505.       /* Make the increased hash table empty.  The entries are still
  506.      available in htab->entry_tab.  */
  507.  
  508.       hash_reset ();
  509.  
  510.       /* Go through the entries and install them in the pointer vector
  511.      htab->hash.  The items are actually inserted in htab->entry_tab at
  512.      the position where they already are.  The htab->coll_link need
  513.      however be updated.  Could be made a little more efficient.  */
  514.  
  515.       for (ep = htab_r->entry_tab; i > 0; i--)
  516.     {
  517.       hash_insert2 (htab_r, ep->ino, ep->dev);
  518.       ep++;
  519.     }
  520.     }
  521.  
  522.   return hash_insert2 (htab_r, ino, dev);
  523. }
  524.  
  525.  
  526. /* Insert INO and DEV in the hash structure HTAB, if not
  527.    already present.  Return zero if inserted and non-zero if it
  528.    already existed.  */
  529.  
  530. int
  531. hash_insert2 (htab, ino, dev)
  532.      struct htab *htab;
  533.      ino_t ino;
  534.      dev_t dev;
  535. {
  536.   struct entry **hp, *ep2, *ep;
  537.   hp = &htab->hash[ino % htab->modulus];
  538.   ep2 = *hp;
  539.  
  540.   /* Collision?  */
  541.  
  542.   if (ep2 != NULL)
  543.     {
  544.       ep = ep2;
  545.  
  546.       /* Search for an entry with the same data.  */
  547.  
  548.       do
  549.     {
  550.       if (ep->ino == ino && ep->dev == dev)
  551.         return 1;        /* Found an entry with the same data.  */
  552.       ep = ep->coll_link;
  553.     }
  554.       while (ep != NULL);
  555.  
  556.       /* Did not find it.  */
  557.  
  558.     }
  559.  
  560.   ep = *hp = &htab->entry_tab[htab->first_free_entry++];
  561.   ep->ino = ino;
  562.   ep->dev = dev;
  563.   ep->coll_link = ep2;        /* `ep2' is NULL if no collision.  */
  564.  
  565.   return 0;
  566. }
  567.  
  568.  
  569.  
  570. /* Initialize the struct string S1 for holding SIZE characters.  */
  571. void
  572. str_init (s1, size)
  573.      string *s1;
  574.      unsigned size;
  575. {
  576.   string s;
  577.  
  578.   s = (string) xmalloc (sizeof (stringstruct));
  579.   s->text = xmalloc (size + 1);
  580.  
  581.   s->alloc = size;
  582.   *s1 = s;
  583. }
  584.  
  585.  
  586. static void
  587. ensure_space (s, size)
  588.      string s;
  589.      unsigned size;
  590. {
  591.   if (s->alloc < size)
  592.     {
  593.       s->text = xrealloc (s->text, size + 1);
  594.       s->alloc = size;
  595.     }
  596. }
  597.  
  598.  
  599. /* Assign the null-terminated C-string CSTR to S1.  */
  600. void
  601. str_copyc (s1, cstr)
  602.      string s1;
  603.      char *cstr;
  604. {
  605.   unsigned l = strlen (cstr);
  606.   ensure_space (s1, l);
  607.   strcpy (s1->text, cstr);
  608.   s1->length = l;
  609. }
  610.  
  611.  
  612. void
  613. str_concatc (s1, cstr)
  614.      string s1;
  615.      char *cstr;
  616. {
  617.   unsigned l1 = s1->length;
  618.   unsigned l2 = strlen (cstr);
  619.   unsigned l = l1 + l2;
  620.  
  621.   ensure_space (s1, l);
  622.   strcpy (s1->text + l1, cstr);
  623.   s1->length = l;
  624. }
  625.  
  626.  
  627. /* Truncate the string S1 to have length LENGTH.  */
  628. void
  629. str_trunc (s1, length)
  630.      string s1;
  631.      unsigned length;
  632. {
  633.   if (s1->length > length)
  634.     {
  635.       s1->text[length] = 0;
  636.       s1->length = length;
  637.     }
  638. }
  639.  
  640. /* Allocate `n' bytes of memory dynamically, with error checking.  */
  641.  
  642. char *
  643. xmalloc (n)
  644.      unsigned n;
  645. {
  646.   char *p;
  647.  
  648.   p = malloc (n);
  649.   if (p == 0)
  650.     error (1, 0, "virtual memory exhausted");
  651.   return p;
  652. }
  653.  
  654. /* Change the size of an allocated block of memory `p' to `n' bytes,
  655.    with error checking.
  656.    If `p' is NULL, run xmalloc.
  657.    If `n' is 0, run free and return NULL.  */
  658.  
  659. char *
  660. xrealloc (p, n)
  661.      char *p;
  662.      unsigned n;
  663. {
  664.   if (p == 0)
  665.     return xmalloc (n);
  666.   if (n == 0)
  667.     {
  668.       free (p);
  669.       return 0;
  670.     }
  671.   p = realloc (p, n);
  672.   if (p == 0)
  673.     error (1, 0, "virtual memory exhausted");
  674.   return p;
  675. }
  676.